﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using LogLib;

namespace PhotoNamingService
{
    public class NamingService
    {
        protected string _error = "";
        public string ErrorMessage
        {
            get
            {
                return _error;
            }
        }

        private IPhotoNaming _naming = null;

        public NamingService()
        {
            CreatNamingObject();
        }

        /// <summary>
        /// 根据配置中的命令方式名称创建命名对象
        /// </summary>
        private void CreatNamingObject()
        {
            PhotoNameConfig option = PhotoNamingBase.Option;
            string fullTypeName = string.Format("{0}.{1}", this.GetType().Namespace, option.NamingType);
            Assembly assembly = Assembly.GetExecutingAssembly();
            Type type = assembly.GetType(fullTypeName);
            if (type == null)
            {
                _error = "无法获取对象名称:" + fullTypeName;
                Log.WriteAsync(_error);
                throw new Exception(_error);
            }
            object instance = Activator.CreateInstance(type);
            if (instance == null)
            {
                _error = "创建类型对象失败:" + type.FullName.ToString();
                Log.WriteAsync(_error);
                throw new Exception(_error);
            }
            _naming = instance as IPhotoNaming;
            if (_naming != null)
            {
                string info = string.Format("照片命名对象创建成功: {0}",  _naming.GetType().FullName);
                Log.WriteAsync(info);
            }      
        }

        public string GetPhotoName(string inParams)
        {
            if(_naming == null)
            {
                _error = "命名对象为空.";
                Log.WriteAsync(_error);
                throw new Exception(_error);
            }
            string photoName = "";
            if (!_naming.GetPhotoName(inParams, out photoName))
            {
                throw new Exception(_naming.ErrorMessage);
            }
            return photoName;
        }
    }
}
